import re

from passlib.hash import md5_crypt
from passlib.hash import sha256_crypt
from passlib.hash import sha512_crypt


class crypt_pass:

    def passlibCrypt(self, password, salt=None):
        if not isinstance(password, str):
            raise ImportError("The password is not str")

        if password is None or len(password) == 0:
            raise ImportError("The password is not empty")

        if salt is not None and not isinstance(salt, str):
            raise ImportError("The salt is not str")

        passlibEncrypt = None
        log = ""
        if salt is None:
            log = "随机盐"
            result = sha512_crypt.hash(password, salt=salt, rounds=5000)
            print(log, result)
            return result

        if salt.startswith("$1$"):
            passlibEncrypt = md5_crypt
            log = "MD5"
        elif salt.startswith("$5$"):
            passlibEncrypt = sha256_crypt
            log = "SHA-256"
        elif salt.startswith("$6$"):
            passlibEncrypt = sha512_crypt
            log = "SHA-512"

        if passlibEncrypt == md5_crypt:
            standard_salt = re.compile(r"^\$1\$([\\.\\/a-zA-Z0-9]{1,8}).*")
            match = standard_salt.match(salt)
            extra_salt = match.group(1)
            result = passlibEncrypt.hash(password, salt=extra_salt)
        else:
            standard_salt = re.compile("^\\$([56])\\$(rounds=(\\d+)\\$)?([\\.\\/a-zA-Z0-9]{1,16}).*")
            match = standard_salt.match(salt)
            extra_salt = match.group(4)
            result = passlibEncrypt.hash(password, salt=extra_salt, rounds=5000)


        return result

if __name__ == '__main__':
    crypt_pass().passlibCrypt("123.com","$6$1gq8PHf//slNT/T8")
    
